﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

using Microsoft.AspNetCore.Http;

using Newtonsoft.Json;

using Utils;

namespace MicroApi.Core.WebSockets
{
    public class WebSocketConnectionManager
    {

        private readonly List<WebSocketConnection> connections = new List<WebSocketConnection>();


        internal static readonly JsonSerializerSettings jsonSerializerSettings = JsonHelper.DefaultJsonSerializerSettings;

        /// <summary>
        /// 开始webstock
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="webSocketService">服务</param>
        /// <returns></returns>
        public async Task StartSocket(HttpContext httpContext, object webSocketService, params object[] openArgs)
        {
            if (httpContext.WebSockets.IsWebSocketRequest)
            {
                var connection = new WebSocketConnection(httpContext, this, await httpContext.WebSockets.AcceptWebSocketAsync(), webSocketService, openArgs);
                connections.Add(connection);
                await connection.ReceiveAsync();
            }
            else
            {
                httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
            }
        }

        public void Remove(Guid guid)
        {
            connections.RemoveAll(a => a.Guid == guid);
        }
        public IClientSession All()
        {
            return new ClientSession(connections, jsonSerializerSettings);
        }

        public IClientSession Group(string groupName)
        {
            if (string.IsNullOrEmpty(groupName))
            {
                return All();
            }
            return new ClientSession(connections.Where(a => a.Is(groupName)), jsonSerializerSettings);
        }

    }
}
